package cat.joronya.supermanager.service;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import cat.joronya.supermanager.Supermanager;

import android.content.Context;
import android.net.ConnectivityManager;

/**
 * Creem una AsyncTask per fer el primer GET on veurem
 * si esta tancat el supermanager i d'on guardarem la
 * sessio.
 * 
 * @author pol
 */
public class InitSync extends Object//AsyncTask<Void,Void,DefaultHttpClient>
{
	// Base GET
	public static final String BASE_URL = "http://supermanager.acb.com";
	
	// el service
	private SupermanagerService service;
	
	// status de l'init
	public int status = -1;
	
	/**
	 * Constructor amb el service que el crida, i l'intent que executem.
	 * @param intentService
	 */
	public InitSync(SupermanagerService service)
	{
		this.service = service;
	}
	
	protected DefaultHttpClient execute()//doInBackground(Void... params) 
	{
		try
		{
			// check de connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();
			
			if( !online )
				throw new ConnectivityException();

			// init de session
			DefaultHttpClient client = new DefaultHttpClient();
			
			HttpGet firstHttpGet = new HttpGet(BASE_URL);
			client.execute(firstHttpGet);
			
			//TODO: mirar si retorna login o pantalla "cerrado temporalmente"
			boolean supermanagerTancat = false;
			if( supermanagerTancat )
				throw new ClosedWebException();
		
			// web oberta, pendent de login
			status = Supermanager.PENDING_LOGIN;
			
			// acabem ok, retornem el client
			return client;
		}
		catch(ConnectivityException ce){
			// no hi ha connectivitat, retornem null
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
			return null;
		}
		catch(ClosedWebException cce){
			// web tancada per processament
			status = Supermanager.CLOSED_STATUS;
			return null;
		}
		catch(Exception e){
			// altre error
			status = Supermanager.OTHER_ERROR_STATUS;
			return null;
		}
    }

	/**
	 * Aqui fem l'update de DB per que la part grafica vegi els
	 * valors recuperats.
	 */
    protected void onPostExecute() 
    {
    	// TODO: guardar si pagina tancada
    }
}	
